<?php
/**
 * content.inc.php
 */

if(!defined('IN_SITE') || !defined('IN_ADMIN')) {
	exit('Access Denied');
}
function searchFilter($str) {
	//转义引号
	if(!get_magic_quotes_gpc()) {
		$str = addslashes($str);
	}

	//过滤MySQL特殊符号
	$str = str_replace('[', '[[]', $str);
	$str = str_replace('_', '[_]', $str);
	$str = str_replace('%', '[%]', $str);

	//多个关键字
	if(preg_match('/ /', $str)) {
		$str_arr = array();
		$str_arr = explode(" ", $str);
		return $str_arr;
	}else{
	//一个关键字
		return $str;
	}
}
$op = in_array($op, array('list', 'add', 'edit', 'editsave', 'del', 'getsubcate', 'getnewcontent', 'delattach', 'upload', 'getunuseattach')) ? $op : 'add';
$c = load('content.class.php');

switch ($op) 
{
	case 'list':
		if($cid)
		{
			$query = $db->query("SELECT cid FROM {$tablepre}category WHERE fid='$cid'");
			while ($row = $db->fetch_array($query)) {
				$subcateid[] = $row;
			}
			if($subcateid[0])
			{
				$scid = '';
				foreach ($subcateid as $val)
				{
					$scid .= $val['cid'].',';
				}
				$scid = $scid.$cid;	//substr($scid, 0, -1);
				$where = " WHERE `cateid` IN ($scid)";
				if($keyword)
				{
					$where .= " AND title LIKE '%$keyword%'";
				}
			}
			else
			{
				$where = " WHERE `cateid`='$cid'";
				if($keyword)
				{
					$where .= " AND title LIKE '%$keyword%'";
				}
			}
		}
		else
		{
			$where = " WHERE status > '-1'";
			if($keyword)
			{
				$where .= " AND title LIKE '%$keyword%'";
			}
		}

		$pagesize = 30;
		$order = " ORDER BY pubtime DESC";
		$page = max(intval($page), 1);
		$offset = $pagesize*($page-1);
        $limit = " LIMIT $offset, $pagesize";
        $sql = '';
        $sql .= "SELECT contentid, title, editor, islink, url, pubtime, updatetime, status FROM `{$tablepre}content` $where";
        $num = $db->num_rows($db->query($sql));
        $sql .= " $order $limit";
		$content = $db->fetch_all($sql);
		$pageurl = multi($num, $pagesize, $page, "admincp.php?action=content&op=list&cid=$cid");

		break;
		
	case 'add':
		if($dosubmit)
		{
			require_once SITE_ROOT.'include/upload.class.php';
			require_once SITE_ROOT.'/include/image.class.php';
			$dir = date('y').'/'.date('m');
			$savePath = SITE_ROOT."attachments/".$dir;
			//上传展示图
			if($_FILES['showimg']['tmp_name']) //展示图
			{
				$f = new upload("showimg", $savePath);
				$f->up();
				$img = $f->uploadedfiles;
				$d['showimg'] = $img[0]['filepath'];
			}
			$contentid = $c->add($d);
			tongji(4);
			//更新附件
			if(!$d['islink'] && $localid)
			{
				foreach($localid as $k=>$v){
					$db->query("UPDATE {$tablepre}attach SET contentid='$contentid' WHERE aid='$v'");
				}
				$content = SafeConvert($d['content']);
				$db->query("UPDATE {$tablepre}content SET content='$content', attachment='1' WHERE contentid='$contentid'");
			}

			//生成静态页 非外链并且为发布状态
			if(!$d['islink'] && $d['status'])
			{
				$html = load('html.class.php');
				$html->content($contentid);
			}
			if($contentid) showmessage('发布成功！继续发布。', '?action=content&op=add');
		}

		break;
		
	case 'edit':
		$content = $c->get($contentid);
		//附件
		if($content['attachment'])
		{
			$query = $db->query("SELECT * FROM {$tablepre}attach WHERE contentid='$contentid'");
			while ($row = $db->fetch_array($query)) {
				$attach[] = $row;
			}
		}
		break;
		
	case 'editsave':
		if($dosubmit)
		{
			require_once SITE_ROOT.'include/upload.class.php';
			require_once SITE_ROOT.'include/image.class.php';
			$dir = date('y').'/'.date('m');
			$savePath = SITE_ROOT."attachments/".$dir;

			//上传展示图
			if($_FILES['showimg']['tmp_name']) //展示图
			{
				$f = new upload("showimg", $savePath);
				$f->up();
				$img = $f->uploadedfiles;

				$d['showimg'] = $img[0]['filepath'];
			}
			$contentid = $c->edit($d);
			tongji(5);

			//更新附件
			if(!$d['islink'] && $localid)
			{
				foreach($localid as $k=>$v){
					$db->query("UPDATE {$tablepre}attach SET contentid='$contentid' WHERE aid='$v'");
				}
				$content = SafeConvert($d['content']);
				$db->query("UPDATE {$tablepre}content SET content='$content', attachment='1' WHERE contentid='$contentid'");
			}
			//生成静态页
			if(!$islink && $d['status'])
			{
				$html = load('html.class.php');
				$html->content($contentid);
			}
			if($contentid) showmessage('修改成功！', "?action=content&op=edit&contentid=$d[contentid]");
		}
		break;
		
	case 'del':
		if($delsubmit)
		{
			$cateid = $c->del($contentid);
			tongji(6,$cateid);
			if($cateid) showmessage("删除成功！", "?action=content&op=list&cateid=$cateid");
		}
		break;
		
	case 'getsubcate':
		if(empty($cid)) return false;
		$category = load("category.class.php");
		$subcate = $category->getsubcate($cid);
	
	
		if(!empty($subcate))
		{
			$html .= '<select name="d[subcateid]" '.">\n";
			$html .= "<option value=\"\">---请选择子类---</option>\n";
			for($i=0; $i<count($subcate); $i++)
			{
				$selected = $subcate[$i]['cid'] == $subcateid ? 'selected="selected"' : '';
				$html .= "<option value=\"".$subcate[$i]['cid']."\" $selected>".$subcate[$i]['cname']."</option>\n";
			}
			$html .= '</select>';
		}
		//header("Content-type: text/html; charset=GBK");
		exit($html);
		break;
		
	case 'delattach':
		if(empty($aid)) return false;
		$filepath = $db->result_first("SELECT filepath FROM `{$tablepre}attach` WHERE aid='$aid'");
		@unlink(SITE_ROOT.'attachments'.$filepath);
		$query = $db->query("DELETE FROM `{$tablepre}attach` WHERE aid='$aid'");
		$html = $query ? 'ok' : 'error';
		//header("Content-type: text/html; charset=GBK");
		exit($html);
		break;
	case 'upload';
		require_once SITE_ROOT.'include/upload.class.php';
		require_once SITE_ROOT.'/include/image.class.php';
		$dir = date('y').'/'.date('m');
		$savePath = SITE_ROOT . 'attachments/'.$dir;
		if (!empty($_FILES)) {
			$i = new image();
			$f = new upload("Filedata", $savePath);
			$f->up();
			$img = $f->uploadedfiles;
			$filename = $img[0]['filename'];
			$isimage = in_array($img[0]['fileext'], array('jpg','gif','png','jpeg','bmp')) ? 1 : 0;
//			if($isimage){
//				$i->watermark(SITE_ROOT."attachments/".$img[0]['filepath'],'',0);
//			}
			$db->query("INSERT INTO {$tablepre}attach(contentid, uid, filename, filetype, filesize, filepath, isimage, pubtime) VALUES('$contentid', '{$administrator['id']}', '$filename', '{$img[0]['fileext']}', '{$img[0]['filesize']}', '{$img[0]['filepath']}', '$isimage', '$timestamp')");
			$aid = $db->insert_id();
			$html="<tr  id=\"a_$aid\"><td><a href=\"javascript:void(0)\" onclick=\"delattach($aid)\">[删除]</a>　<a href=\"javascript:void(0)\" onmouseover=\"ShowDiv($aid)\" onmouseout=\"CloseDiv($aid)\">$filename</a>　<a href=\"javascript:void(0)\" onclick=\"Insertpic1('";
			if(in_array($img[0]['fileext'], array('jpg','gif','png','jpeg','bmp'))){
				$html .= "<img src={$siteurl}/attachments{$img[0]['filepath']}>";
			}elseif(in_array($img[0]['fileext'], array('rar','zip'))){
				$html .= "<a href={$siteurl}/attachments/{$img[0]['filepath']}><img src={$siteurl}images/attachicons/rar.gif style=border:0px></a>";
			}elseif($img[0]['fileext']=='swf'){
				$html .= "<embed height=400 type=application/x-shockwave-flash width=480 src={$siteurl}attachments{$img[0]['filepath']} loop=true play=true menu=false bgcolor=#ffffff quality=high wmode=opaque>";
			}
			$html .= "')\">[插入]</a><input type=\"hidden\" name=\"localid[]\" value=\"$aid\"></td><td>";
			if($isimage){
				$html .= "<div style=\"border:1px solid #DADADA;width:250px;height:auto; position:absolute; text-align:center; background-color:#FFFFFF; display:none; padding:8px; margin-left:5px; z-index:99;\" id=\"$aid\"><img src=\"{$siteurl}attachments{$img[0]['filepath']}\" width=\"200\" height=\"200\"  border=\"0\"  /></div>";
		}
			$html .= "</td></tr>";
		}
		//header("Content-type: text/html; charset=GBK");
		//$html = iconv("gbk", "UTF-8",$html);
		exit($html);
		break;
	case 'getunuseattach';
		$unuseattach = $db->fetch_all("SELECT aid, filename, filepath, filetype, isimage FROM {$tablepre}attach WHERE uid='{$administrator['id']}' AND contentid='0'");
		if($unuseattach){
			$html = '';
			foreach($unuseattach as $k=>$v){
			$html .= "<tr  id=\"a_{$v['aid']}\"><td><a href=\"javascript:void(0)\" onclick=\"delattach({$v['aid']})\">[删除]</a>　<a href=\"javascript:void(0)\" onmouseover=\"ShowDiv({$v['aid']})\" onmouseout=\"CloseDiv({$v['aid']})\">{$v['filename']}</a>　<a href=\"javascript:void(0)\" onclick=\"Insertpic1('";
			if(in_array($v['filetype'], array('jpg','gif','png','jpeg','bmp'))){
				$html .= "<img src={$siteurl}attachments{$v['filepath']}>";
			}elseif(in_array($v['filetype'], array('rar','zip'))){
				$html .= "<a href={$siteurl}attachments{$v['filepath']}><img src={$siteurl}images/attachicons/rar.gif style=border:0px></a>";
			}elseif($v['filetype']=='swf'){
				$html .= "<embed height=400 type=application/x-shockwave-flash width=480 src={$siteurl}attachments{$v['filepath']} loop=true play=true menu=false bgcolor=#ffffff quality=high wmode=opaque>";
			}
			$html .= "')\">[插入]</a><input type=\"hidden\" name=\"localid[]\" value=\"{$v['aid']}\"></td><td>";
			if($v['isimage']){
				$html .= "<div style=\"border:1px solid #DADADA;width:250px;height:auto; position:absolute; text-align:center; background-color:#FFFFFF; display:none; padding:8px; margin-left:5px; z-index:99;\" id=\"{$v['aid']}\"><img src=\"{$siteurl}attachments{$v['filepath']}\" width=\"200\" height=\"200\"  border=\"0\"  /></div>";
			}
			$html .= "</td></tr>";
			}
			//header("Content-type: text/html; charset=GBK");
		}
		exit($html);
		break;
}

$cachefile = CACHE_PATH.'cache_category.php';
if(is_file($cachefile))
{
	@include $cachefile;
}
else
{
	updatecache('category');
	@include $cachefile;
}
$cate = $_SCACHE['category'];
include admin_tpl("content");
?>